package org.jeecg.modules.rooms.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.modules.business.entity.BusHotel;
import org.jeecg.modules.business.service.impl.BusHotelServiceImpl;
import org.jeecg.modules.rooms.DTO.CesHourRoomRuleDto;
import org.jeecg.modules.rooms.DTO.CesHourRoomRuleModifyDto;
import org.jeecg.modules.rooms.Vo.CesHourRoomRuleVo;
import org.jeecg.modules.rooms.entity.CesHourRoomRule;
import org.jeecg.modules.rooms.mapper.CesHourRoomRuleMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 钟点房计费规则表 服务实现类
 * </p>
 *
 * @author Claude
 * @since 2023-03-08
 */
@Service
public class CesHourRoomRuleServiceImpl extends ServiceImpl<CesHourRoomRuleMapper, CesHourRoomRule> implements IService<CesHourRoomRule> {

    @Resource
    CesHourRoomRuleMapper cesHourRoomRuleMapper;
    @Resource
    BusHotelServiceImpl busHotelService;


    public Result list(CesHourRoomRuleDto cesHourRoomRuleDto){

        QueryWrapper<CesHourRoomRule> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq(CesHourRoomRule.HOTEL_ID,cesHourRoomRuleDto.getHotelId());
        if (StringUtils.isNotEmpty(cesHourRoomRuleDto.getHourRoomName())){
            //处理百分号 mybatis plus bug 查询 % 出现全量数据
            queryWrapper.like(CesHourRoomRule.HOUR_ROOM_NAME, CommonUtils.escapeChar(cesHourRoomRuleDto.getHourRoomName()));
        }
        queryWrapper.eq(CesHourRoomRule.INVALID,false);
        queryWrapper.orderByDesc(CesHourRoomRule.UPDATEAT);
        IPage<CesHourRoomRule> dataPage = cesHourRoomRuleMapper.selectPage(new Page<>(cesHourRoomRuleDto.getPageNo().intValue(),cesHourRoomRuleDto.getPageSize().intValue()),queryWrapper);
        List<CesHourRoomRule> records = dataPage.getRecords();
        List<String> hotelIds = records.stream().map(v-> v.getHotelId()).collect(Collectors.toList());

        List<BusHotel> busHotels = busHotelService.findHotelsByIds(hotelIds.stream().distinct().collect(Collectors.toList()));
        List<CesHourRoomRuleVo> vos = new ArrayList<>();
        records.forEach(v -> {
            CesHourRoomRuleVo vo = new CesHourRoomRuleVo();
            BeanUtil.copyProperties(v, vo);
            Optional<BusHotel> busHotelOptional = busHotels.stream().filter(busHotel -> busHotel.getId().equals(v.getHotelId())).findFirst();
            if(busHotelOptional.isPresent())  vo.setHotelName(busHotelOptional.get().getName());
            vos.add(vo);
        });
        Map<String,Object> map = new HashedMap();
        map.put("records",vos);
        map.put("total",dataPage.getTotal());
        return Result.OK(map);
    }

    public Result create(CesHourRoomRuleModifyDto dto) {
        //新增时默认没有关联任何房型
        dto.setCreateAt(LocalDateTime.now());
        dto.setUpdateAt(LocalDateTime.now());
        dto.setInvalid(false);
        cesHourRoomRuleMapper.insert(dto);
        return Result.ok("创建成功!");
    }

    public Result modify(CesHourRoomRuleModifyDto dto) {
        CesHourRoomRule cesHourRoomRule = cesHourRoomRuleMapper.selectOne(new QueryWrapper<CesHourRoomRule>()
                .eq(CesHourRoomRule.ID, dto.getId())
                .eq(CesHourRoomRule.INVALID, false));
        if (ObjectUtils.isEmpty(cesHourRoomRule)){
            return Result.ok("数据未找到!");
        }
        BeanUtil.copyProperties(dto,cesHourRoomRule, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        cesHourRoomRule.setUpdateAt(LocalDateTime.now());
        cesHourRoomRuleMapper.updateById(cesHourRoomRule);
        return Result.ok("修改成功!");
    }

    public Result batchDelete(List<String> ids) {
        List<CesHourRoomRule> cesHourRoomRules = cesHourRoomRuleMapper.selectBatchIds(ids);
        if (CollectionUtil.isEmpty(cesHourRoomRules)){
            //查不到证明已经被删除过了
            return Result.ok("删除成功!");
        }
        cesHourRoomRules.forEach(v->{
            v.setUpdateAt(LocalDateTime.now());
            v.setInvalid(true);
        });
        saveOrUpdateBatch(cesHourRoomRules);
        return Result.ok("删除成功!");
    }

    public Result deleteOne(String id) {
        CesHourRoomRule cesHourRoomRule = cesHourRoomRuleMapper.selectOne(new QueryWrapper<CesHourRoomRule>()
                .eq(CesHourRoomRule.ID, id)
                .eq(CesHourRoomRule.INVALID, false));
        if (ObjectUtils.isEmpty(cesHourRoomRule)){
            return Result.ok("删除成功!");
        }
        cesHourRoomRule.setUpdateAt(LocalDateTime.now());
        cesHourRoomRule.setInvalid(true);
        cesHourRoomRuleMapper.updateById(cesHourRoomRule);
        return  Result.ok("删除成功!");
    }


    public Result relateLayout(CesHourRoomRuleModifyDto dto) {
        CesHourRoomRule cesHourRoomRule = cesHourRoomRuleMapper.selectOne(new QueryWrapper<CesHourRoomRule>()
                .eq(CesHourRoomRule.ID, dto.getId())
                .eq(CesHourRoomRule.INVALID, false));
        if (ObjectUtils.isEmpty(cesHourRoomRule)){
            return Result.error("该钟点房规则不存在！");
        }
        cesHourRoomRule.setLayoutIds(dto.getLayoutIds());
        cesHourRoomRule.setUpdateAt(LocalDateTime.now());
        if (StringUtils.isBlank(cesHourRoomRule.getLayoutIds())){
            cesHourRoomRuleMapper.update(cesHourRoomRule,new UpdateWrapper<CesHourRoomRule>().lambda()
                    .set(CesHourRoomRule::getLayoutIds,null)
                    .eq(CesHourRoomRule::getId,dto.getId()));
        }else{
            cesHourRoomRuleMapper.updateById(cesHourRoomRule);
        }

        return Result.OK("关联房型成功！");
    }
}
